const exp = require('express');
const bodyParser = require('body-parser');
const app = exp();

app.use(
  exp.static('build'),
  exp.static('dist'),
  bodyParser.json(),
  bodyParser.urlencoded({extended: false})
);

app.use('/api', require('./index'));

app.use(
  function (req, res) {
    res.format({
      'text/html': () => {
        res.redirect('/index.html');
      },
      'default': () => {
        res.status(404).json({message: 'Not found.'})
      }
    })
  },
  function (err, req, res, next) {
    if (res.statusCode < 400)
      res.status(500);

    res.json({message: err.message});
    console.error(err);
  }
);

const server = require('http').createServer(app);
require('./socket')(server);
server.listen(3000);

if (!module.parent) {
  const fs = require('fs');
  const https = require('https');
  const server = https.createServer({
    key: fs.readFileSync('../key.pem'),
    cert: fs.readFileSync('../cer.pem')
  }, app).listen(443);

  require('./socket')(server);
}
